package com.dubito.dao.impl;

import org.apache.ibatis.session.SqlSession;

import com.dubito.utils.MyBatisUtil;

public abstract class BaseDaoImpl<T> {

	public static final String SQL_INSERT = "insert";
	public static final String SQL_SELECT = "select";
	SqlSession session=null;
	
	public int insert(T t){
		int i = 0;
		try {
			session = MyBatisUtil.getSession();
			i = session.insert(getStatement(SQL_INSERT), t);
			session.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.rollback();
		}finally {
			try {
				MyBatisUtil.closeSession();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		
		return i;
	}
	
	public T select(T t){
		try {
			session = MyBatisUtil.getSession();
			t = session.selectOne(getStatement(SQL_SELECT), t);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				MyBatisUtil.closeSession();
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		
		return t;
	}
	

	public String getStatement(String sqlId) {
		String name = this.getClass().getName();
		StringBuilder sb = new StringBuilder();
		sb.append(name).append(".").append(sqlId);
		return sb.toString();
	}
}
